package cn.ytxy.ivos.audit.service.impl;


import cn.ytxy.ivos.application.mapper.ApplicationMapper;
import cn.ytxy.ivos.application.pojo.entity.Application;
import cn.ytxy.ivos.audit.mapper.AuditMapper;
import cn.ytxy.ivos.audit.pojo.dto.AuditQuery;
import cn.ytxy.ivos.audit.pojo.dto.AuditSaveParam;
import cn.ytxy.ivos.audit.pojo.entity.Audit;
import cn.ytxy.ivos.audit.pojo.vo.AuditVO;
import cn.ytxy.ivos.audit.service.AuditService;
import cn.ytxy.ivos.base.enums.ApplicationStatusEnum;
import cn.ytxy.ivos.base.enums.AuditStatusEnum;
import cn.ytxy.ivos.user.mapper.UserMapper;
import cn.ytxy.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @ClassName AuditServiceImpl
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/5/13 9:29
 * @Version 1.0
 */

@Slf4j
@Transactional
@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplicationMapper applicationMapper;

    @Override
    public void insertAudit(Application application) {
        log.debug("为申请单生成对应的审批单业务：application={}", application);
        //1.获取审批人id集合
        List<Long> userIdList = application.getAuditUserIdList();
        //2.遍历审批人集合，有几个审批人，就生成几条审批数据
        for (int i = 0; i < userIdList.size(); i++) {
            //设置当前审批单的相关数据
            Audit audit = new Audit();
            audit.setApplicationId(application.getId());//设置申请单id
            audit.setAuditUserId(userIdList.get(i));//设置审批人id
            audit.setAuditSort(i);//设置审批次序 直属领导次序为0 上上级次序为1
            //4.设置每条审批单的状态
            if (i == 0) {
                //0表示为第1条审批数据，直属领导的审批单状态为“待我审核”
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());//直属领导审批中
            } else {
                //1表示为第2条审批数据，上上级领导的审批单状态为“待他人审核”
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());//上上级审批中
            }
            //5.设置创建时间
            audit.setCreateTime(new Date());
            //6.每循环一次，向数据库插入一条审批数据
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        return auditMapper.selectAuditByApplicationId(id);
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
        //获取审批人名称
        if (auditVOList != null && !auditVOList.isEmpty()) {
            auditVOList.forEach(this::assignAuditUserList);
        }
        return auditVOList;
    }


    private void assignAuditUserList(AuditVO auditVO) {
        //新建2个空数组存放审批人名称和审批人id
        ArrayList<String> auditUsernameList = new ArrayList<>();
        ArrayList<Long> auditUserIdList = new ArrayList<>();
        //1.根据审批单的id查询审批人id集合
        List<AuditVO> auditVOS = auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //遍历查询出来的审批人集合
        auditVOS.forEach(audit -> {
            //将审批人的id存放到集合中
            auditUserIdList.add(audit.getAuditUserId());
            //根据审批人的id去userMapper查询审批人的名称
            UserVO userVO = userMapper.selectById(audit.getAuditUserId());
            auditUsernameList.add(userVO.getUsername());
        });
        //将审批人的名称使用拼接工具进行拼接并返回
        StringJoiner stringJoiner = new StringJoiner(",");
        auditUsernameList.forEach(stringJoiner::add);
        auditVO.setAuditUserIdList(auditUserIdList);
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("更新审批单(通过/驳回)业务：auditSaveParam={}", auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam, audit);
        audit.setUpdateTime(new Date());
        //找到当前审批对应的申请单对象
        Application application = new Application();
        application.setId(auditSaveParam.getApplicationId());
        application.setUpdateTime(new Date());
        //判断前端传过来的审批状态是通过还是驳回，分别针对不同的审批操作进行后续的处理
        if (audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())) {
            //审批通过
            //更新当前审批单
            auditMapper.update(audit);
            /*继续查询其他的审批单，与当前审批单审核同一个申请单的审批单*/
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(auditSaveParam.getApplicationId());
            //根据申请单id查询当前申请单对应的所有未审批的审批单总数（注意：当前审批单已审批通过）
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if (count>0){//有未审批的审批单
                //下一条审批单是当前审批单的次序+1
                auditQuery.setAuditSort(auditSaveParam.getAuditSort()+1);
                //根据申请单id与审批次序查出来下一条
                List<AuditVO> auditVOS = auditMapper.selectAudit(auditQuery);
                if (auditVOS!=null&&!auditVOS.isEmpty()){
                    AuditVO auditVO = auditVOS.get(0);
                    //创建第二个空的审批对象，准备更新数据库
                    Audit audit1 = new Audit();
                    audit1.setId(auditVO.getId());
                    audit1.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    auditMapper.update(audit1);
                }
                //设置申请单状态为审核中
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else {//没有未审批的审批单
                //设置申请单的状态为已审核（后续可以分配车辆了）
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }

        } else if (audit.getAuditStatus().equals(AuditStatusEnum.REJECT.getCode())) {//审批驳回
            //删除审批单，修改申请单状态为驳回
            auditMapper.update(audit);//更新当前审批单 驳回状态 驳回原因 更新时间
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            //根据申请单id，查到审批次申请单的所有审批单vo对象
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            //判断是否能查到审批单
            if(auditVOList !=null && auditVOList.size()>0){
                for(int i = 0; i<auditVOList.size(); i++){
                    AuditVO auditVO = auditVOList.get(i);
                    if(AuditStatusEnum.PENDING.getCode().equals(auditVO.getAuditStatus())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            //设置申请单的状态为已驳回，并设置驳回原因
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
        }
    }
}
